package han.cirno.corrupt.modules.nofy

import androidx.activity.compose.LocalActivity
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import han.cirno.corrupt.compose.localeStringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import han.cirno.corrupt.Application
import han.cirno.corrupt.R
import han.cirno.corrupt.activity.GlobalViewModel
import han.cirno.corrupt.compose.QuickCard
import han.cirno.corrupt.compose.TitleTextWithIcon
import han.cirno.corrupt.compose.VerticalSpacer

@Composable
fun NofyLayout()= Column(modifier = Modifier
    .fillMaxSize()
    .padding(horizontal = 16.dp)
    .verticalScroll(rememberScrollState())){
    val globalViewModel:GlobalViewModel= hiltViewModel(LocalActivity.current as AppCompatActivity)
    val broadcastLongitude by globalViewModel.configLongitude.observeAsState("-")
    val broadcastLatitude by globalViewModel.configLatitude.observeAsState("-")
    val configMode by globalViewModel.configMode.observeAsState("-")
    val position = remember { fetchPositions() }
    var editLongitude by remember { mutableStateOf(broadcastLongitude) }
    var editLatitude by remember { mutableStateOf(broadcastLatitude) }
    val context =  LocalContext.current
    var longitudeError by remember { mutableStateOf(false) }
    var latitudeError by remember { mutableStateOf(false) }
    Card (
        modifier = Modifier.padding(0.dp,4.dp),
        onClick = {
        GlobalViewModel.sendCheckBroadcast(context)
    }) {
        Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
            TitleTextWithIcon(
                iconRes = R.drawable.baseline_info_24,
                textRes = R.string.nofy_status_title
            )
            VerticalSpacer(8.dp)
            Text(text = localeStringResource(
                R.string.nofy_status_configs,
                broadcastLongitude, broadcastLatitude, configMode))
            Text(text= localeStringResource(R.string.nofy_status_broadcast_check))
        }
    }
    QuickCard {
        TitleTextWithIcon(
            iconRes = R.drawable.baseline_edit_24,
            textRes = R.string.nofy_edit_title
        )
        VerticalSpacer(8.dp)
        Column {
            OutlinedTextField(
                modifier = Modifier.fillMaxWidth(),
                value = editLongitude,
                onValueChange = {editLongitude=it},
                label = {
                    Text(text= localeStringResource(R.string.nofy_edit_hint_longitude),
                    style=MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace)) },
                textStyle = MaterialTheme.typography.bodyLarge.copy(fontFamily = FontFamily.Monospace),
                singleLine = true,
                isError = longitudeError)
            OutlinedTextField(
                modifier = Modifier.fillMaxWidth(),
                value = editLatitude,
                onValueChange = {editLatitude=it},
                label = {
                    Text(
                        text= localeStringResource(R.string.nofy_edit_hint_latitude),
                        style=MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace)) },
                textStyle = MaterialTheme.typography.bodyLarge.copy(fontFamily = FontFamily.Monospace),
                singleLine = true,
                isError = latitudeError)
        }
        VerticalSpacer(8.dp)
        Button(onClick = {
            val latitude = editLatitude?.toDoubleOrNull()
            val longitude = editLongitude?.toDoubleOrNull()
            latitudeError=latitude==null||latitude !in -90.0 ..90.0
            longitudeError=longitude==null||longitude !in -180.0..180.0
            if (latitudeError||longitudeError||latitude==null||longitude==null)return@Button
            GlobalViewModel.sendEditBroadcast(context,longitude, latitude)
            GlobalViewModel.sendCheckBroadcast(context)
        },
            modifier = Modifier.fillMaxWidth().padding(horizontal = 32.dp)) {
            Text(text= localeStringResource(R.string.submit))
        }
    }
    QuickCard {
        TitleTextWithIcon(
            iconRes = R.drawable.baseline_place_24,
            textRes = R.string.nofy_presets_title
        )
        VerticalSpacer(8.dp)
        Column {
            position.forEach {
                OutlinedCard (
                    modifier = Modifier
                        .padding(2.dp)
                        .fillMaxWidth(),
                    onClick = {
                        editLongitude=it.second
                        editLatitude=it.third
                    }){
                    Column(modifier = Modifier.padding(16.dp)) {
                        Text(text = it.first, style = MaterialTheme.typography.bodyLarge)
                        Text(text = "${it.second},${it.third}", style = MaterialTheme.typography.bodyMedium)
                    }
                }
            }
        }
    }
}

fun fetchPositions():List<Triple<String,String,String>>{
    val strings=String(Application.application.resources.assets.open("loco.csv")
        .use { it.readBytes() })
    return strings.lines().map {
        val split = it.split(",")
        Triple(split[0],split[1],split[2])
    }
}